using MediatR;
using Medical.Api.Read.Application.Command.BasicManagement.DeviceClassificationDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Read.Application.Handler.BasicManagement.DeviceClassificationDictionaryHandler
{
    /// <summary>
    /// 查询器械列表处理器
    /// </summary>
    public class QueryApparatusHandler : IRequestHandler<QueryApparatusCommand, ApiResult<ApiPageIng<Apparatus>>>
    {
        private readonly IBaseRepository<Apparatus> _apparatusRepository;
        private readonly ILogger<QueryApparatusHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="apparatusRepository">器械仓储</param>
        /// <param name="logger">日志记录器</param>
        public QueryApparatusHandler(
            IBaseRepository<Apparatus> apparatusRepository,
            ILogger<QueryApparatusHandler> logger)
        {
            _apparatusRepository = apparatusRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理查询器械列表请求
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页器械列表</returns>
        public Task<ApiResult<ApiPageIng<Apparatus>>> Handle(QueryApparatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询器械列表");

                // 构建查询条件
                var query = _apparatusRepository.GetAll().Where(x => !x.IsDeleted);

                // 按名称筛选（如果提供）
                if (!string.IsNullOrWhiteSpace(request.QueryDto.ApparatusName))
                {
                    query = query.Where(x => x.ApparatusName.Contains(request.QueryDto.ApparatusName));
                }

                // 按编码筛选（如果提供）
                if (!string.IsNullOrWhiteSpace(request.QueryDto.ApparatusCode))
                {
                    query = query.Where(x => x.ApparatusCode.Contains(request.QueryDto.ApparatusCode));
                }

                // 按状态筛选（如果提供）
                if (request.QueryDto.Status.HasValue)
                {
                    query = query.Where(x => x.Status == request.QueryDto.Status.Value);
                }

                // 计算总记录数
                int total = query.Count();

                // 分页查询
                var pagedData = query
                    .OrderByDescending(x => x.CreateTime) // 按创建时间降序排序
                    .Skip((request.QueryDto.PageIndex - 1) * request.QueryDto.PageSize)
                    .Take(request.QueryDto.PageSize)
                    .ToList();

                // 构建分页结果
                var pageResult = new ApiPageIng<Apparatus>
                {
                    TotalCount = total,
                    PageData = pagedData
                };

                _logger.LogInformation("成功查询器械列表，总记录数：{TotalCount}", total);

                return Task.FromResult(new ApiResult<ApiPageIng<Apparatus>>
                {
                    Code = ApiEnums.Success,
                    Msg = "查询成功",
                    Data = pageResult
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询器械列表时发生异常");
                return Task.FromResult(new ApiResult<ApiPageIng<Apparatus>>
                {
                    Code = ApiEnums.Fail,
                    Msg = "查询失败：系统内部错误",
                    Data = new ApiPageIng<Apparatus>()
                });
            }
        }
    }
}